import React from 'react';
import { inject, observer } from 'mobx-react';
import { Button, Modal, message } from 'antd';
import { toJS } from 'mobx';
import { WeaTableNew, WeaSwitch } from 'comsMobx';

const WeaTable = WeaTableNew.WeaTable;
import { WeaShare, WeaRightMenu, WeaTop, WeaTab, WeaErrorPage, WeaTools, WeaInput, WeaAlertPage, WeaReqTop, WeaNewScroll, WeaSearchGroup, WeaFormItem, WeaTextarea, WeaUpload, WeaError } from 'ecCom';
import WeaRightLeftLayout from '../comp/weaCrmRightLeft';
import ContacterTrail from './ContacterTrail';
import CustomerContact from '../public/CustomerContact';

const getKey = WeaTools.getKey;
import { WeaLocaleProvider } from 'ecCom';

const getLabel = WeaLocaleProvider.getLabel;
import ModifyRecord from '../log/ModifyRecord';

@inject('contacterViewStore', 'customerCardStore')
@observer
class ContacterView extends React.Component {
  constructor(props) {
    super(props);
    this.setState = {
      contentH: 100,
    };
  }

  componentDidMount() {
    const { location: { query }, contacterViewStore } = this.props;
    const { initContacterInfo } = contacterViewStore;
    initContacterInfo({ operation: 'edit', ...query });
    if (window.location.pathname.indexOf('/spa/crm/mobx/index') >= 0) {
      document.title = getLabel(367, '查看') + getLabel(572, '联系人');
    }
  }

  componentWillReceiveProps(nextProps) {
    const keyOld = this.props.location.key;
    const keyNew = nextProps.location.key;
    // 点击菜单路由刷新组件
    if (keyOld !== keyNew) {
      const { contacterViewStore, location: { query } } = nextProps;
      const { initContacterInfo } = contacterViewStore;
      initContacterInfo({ operation: 'edit', ...query });
    }
  }
    createHeight = () => {
      const contentH = jQuery('.wea-new-top-req-content').height() - 1;
      return contentH;
    }
    componentWillUnmount() {
      const { contacterViewStore } = this.props;
      contacterViewStore.clearStatus();
    }
    render() {
      const { contacterViewStore, location, customerCardStore } = this.props;
      let { title, loading, tableStore, showSearchAd, form, verified, hasRight, tabDatas, detailTabKey, trailinfo, customerId, crmContactStore, contacterId,
        showShareDialog, getRightMenus, controlShareDialog, userId, onlyView, canEdit } = contacterViewStore;
      const formParams = form.getFormParams() || {};
      tabDatas = [
        { title: getLabel(572, '联系人') + getLabel(87, '信息'), key: '1' },

      ];
      if (!onlyView) {
        tabDatas.push({ title: getLabel(84283, '工作轨迹'), key: '2' });
        if (canEdit) {
          tabDatas.push({ title: getLabel(32061, '操作日志'), key: '3' });
        }
      }
      // { title: getLabel(32061,"操作日志"), key: "3" },
      // { title: getLabel(84283, '工作轨迹'), key: "2" },
      if (verified && !hasRight) {
        return (<WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@to3bex`} >
          <div style={{ color: '#000' }}>
            {getLabel(2012, '对不起，您暂时没有权限！')}
          </div>
        </WeaAlertPage>
        );
      }
      const Dom = onlyView ? (<div style={{ marginTop: '1px', background: '#fff', height: '100%' }}>
        <WeaNewScroll
          ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@vz8rty`}
          height={'100%'}
          children={this.getFormCondition()}
        />
      </div>) : (<div style={{ marginTop: '1px' }}>
        <WeaRightLeftLayout
          ecId={`${this && this.props && this.props.ecId || ''}_WeaRightLeftLayout@g85xpt`}
          defaultShowLeft={false}
          leftCom={<WeaRightMenu
            ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@tsh8ia`}
            datas={getRightMenus()}
          >
            <WeaNewScroll
              ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@8sofz1`}
              height={'100%'}
              children={this.getFormCondition()}
            />
          </WeaRightMenu>
          }
        >
          <div className="customer-contact-title">{getLabel(6082, '客户联系')}</div>
          <div className="customer-contact-bottomline" />
          <CustomerContact ecId={`${this && this.props && this.props.ecId || ''}_CustomerContact@kl8b55`} ref="contactlogs" contentStore={crmContactStore} params={{ from: 'base', customerId }} location={location} />
        </WeaRightLeftLayout>
      </div>);

      if (verified && hasRight) {
        return (
          <WeaReqTop
            ecId={`${this && this.props && this.props.ecId || ''}_WeaReqTop@pirq0g`}
            title={title}
            loading={loading}
            icon={<i className="icon-coms-crm" />}
            tabDatas={toJS(tabDatas)}
            selectedKey={detailTabKey}
            onChange={this.changeData.bind(this)}
            iconBgcolor="#96358a"
            buttons={this.getButtons()}
            buttonSpace={10}
            showDropIcon={false}
            dropMenuDatas={[]}

          >
            {
              detailTabKey == '1' && Dom
            }
            {
              <WeaShare
                ecId={`${this && this.props && this.props.ecId || ''}_WeaShare@m7l461`}
                visible={showShareDialog}
                onVisibleChange={bool => controlShareDialog(false)}
                shareParams={{
                  resourcetype: 67, // 当前共享数据的类型（同PC浏览按钮的type，例如: 152: 流程
                  resourceid: contacterId, // 分享数据的id
                }}
                msginfo={[
                  {
                    sharetitle: title, // 消息名片中间一栏显示
                    // desc: customerName,//描述，可以不填
                    linkurl: `/common/chatResource/view.html?resourcetype=67&resourceid=${contacterId}&isfromchatshare=1&sharer=${userId}&firstSharer=${userId}&customerId=${customerId}&moduleid=em`, // 消息链接地址（必填）
                    canforward: 1, // 消息是否允许转发 1：是（默认） 0：否
                    callbackurl: `/api/common/chatResource/addshare?resourcetype=67&resourceid=${contacterId}&isfromchatshare=1&firstSharer=${userId}`, // 消息转发回调地址（非必填）
                    sharetypename: getLabel(520328, '联系人名片'), // 消息名片上一栏  分享消息的标题栏
                    objectName: 'FW:CustomShareMsg',
                    showimage: '/images/p.png',
                    sharetype: 'crm',
                    shareid: contacterId,
                    opentype: 1, // 移动端打开方式 1:app内打开（默认） 2：手机默认浏览器打开
                    opentype_pc: 2, // PC端打开方式 1:应用内打开（默认） 2：PC默认浏览器打开
                  },
                ]}
              />
            }
            {
              detailTabKey == '2' &&
              <ContacterTrail ecId={`${this && this.props && this.props.ecId || ''}_ContacterTrail@rxstkx`} data={trailinfo} />
            }
            {
              detailTabKey == '3' &&
              <ModifyRecord ecId={`${this && this.props && this.props.ecId || ''}_ModifyRecord@8x722h`} contentStore={customerCardStore} location={location} contacterLog={'contacterLog'} />
            }
          </WeaReqTop>);
      }
      return <div />;
    }
    changeData = (key) => {
      const { changeTab } = this.props.contacterViewStore;
      changeTab(key);
    }
    getButtons = (ecId) => {
      const { detailTabKey, canEdit, deleteContracter, contacterId } = this.props.contacterViewStore;

      const { modifyTableStore } = this.props.customerCardStore;
      const btnArr = [];
      {
        detailTabKey == '1' &&
                btnArr.push(<Button
                  ecId={`${ecId}_Button@cokyq3@delete`}
                  type="primary"
                  disabled={!canEdit}
                  style={{ marginRight: '20px' }}
                  onClick={() => {
                    Modal.confirm({
                      title: getLabel(15172, '系统提示'),
                      content: getLabel(83600, '您确认要删除吗？'),
                      okText: getLabel(33703, '确定'),
                      cancelText: getLabel(201, '取消'),
                      onOk() {
                        deleteContracter(contacterId);
                      },
                      onCancel() { },
                    });
                  }}
                >{getLabel(91, '删除')}</Button>);
        detailTabKey == '3' &&
                btnArr.push(<Button
                  ecId={`${ecId}_Button@o15biv@excel`}
                  type="primary"
                  style={{ marginRight: '20px' }}
                  onClick={() => {
                    modifyTableStore.exportAll();
                  }}
                >{getLabel(28343, '导出Excel')}</Button>);
      }


      return btnArr;
    }
    getFormCondition = () => {
      const { condition, form } = this.props.contacterViewStore;
      const { isFormInit } = form;
      const group = [];
      const formParams = form.getFormParams();
      isFormInit && toJS(condition).map((c, i) => {
        const items = [];
        c.items.map((fields, index) => {
          const oldValue = fields.value;
          let isunderline = '';
          if (fields.viewAttr == '1' || (fields.conditionType == 'BROWSER' && fields.browserConditionParam.viewAttr == '1')) { fields.hasBorder = false; isunderline = 'underline'; } // 只读样式控制
          let dom;
          if (fields.conditionType == 'INPUT' || fields.conditionType == 'TEXTAREA') {
            dom = <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@5pifp9@${fields.domkey[0]}`} fieldConfig={fields} form={form} onBlur={(v) => { this.onEditChange2(oldValue, fields, v); }} />;
          } else if (fields.conditionType == 'UPLOAD') {
            const key = getKey(fields);
            const bindObj = form.$(key);
            dom = (<div className="crm-weaupload"><WeaUpload
              ecId={`${this && this.props && this.props.ecId || ''}_WeaUpload@4z72qu@${fields.domkey[0]}`}
              {...bindObj.bind()}
              {...fields}
              {...fields.otherParams}
              uploadId={fields.domkey[0]}
              uploadUrl="/api/crm/common/fileUpload"
              category="0,0,0"
              autoUpload
              showBatchLoad={false}
              showClearAll={false}
              multiSelection
              listType={fields.listType}
              onChange={(ids, lists) => {
                form.updateFields({ [fields.domkey[0]]: { value: `${ids}` } }, false);
                this.onEditChange2(oldValue, fields, `${ids}`);
              }}
              datas={fields.datas || []}
            /></div>);
          } else {
            dom = <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@sxllfi@${fields.domkey[0]}`} fieldConfig={fields} form={form} onChange={this.onEditChange.bind(this, oldValue, fields)} />;
          }
          items.push({
            com: (<WeaFormItem
              ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@ldy8la@${fields.domkey[0]}`}
              label={`${fields.label}`}
              labelCol={{ span: `${fields.labelcol}` }}
              wrapperCol={{ span: `${fields.fieldcol}` }}
              underline={isunderline}
            >
              <div style={{ display: 'table-cell', verticalAlign: 'bottom' }}>
                <WeaError
                  ecId={`${this && this.props && this.props.ecId || ''}_WeaError@lrhyml@${fields.domkey[0]}`}
                  tipPosition="bottom"
                  style={{ width: '100%', display: 'block' }}
                  ref={fields.domkey[0]}
                  error={`${'"' + `${fields.label}` + '"'}${getLabel(21423, '未填写')}`}
                >
                  {dom}
                </WeaError>
              </div>
            </WeaFormItem>),
            colSpan: 1,
          });
        });
        group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@tkf5uv@${i}`} needTigger title={c.title} showGroup={c.defaultshow} items={items} />);
      });
      return group;
    }
    onEditChange(oldvalue = '', field, res) {
      let oldValueSpan = oldvalue;
      if (field.formItemType == 'BROWSER') {
        oldValueSpan = field.showName;
      }
      const { contacterId, contacterEdit, condition, form } = this.props.contacterViewStore;
      const fit = field.conditionType.toUpperCase();
      const fieldName = field.domkey[0];
      const value = res[fieldName].value;
      if (value !== oldvalue) {
        if (field.viewAttr == 3 && value == '') {
          this.refs[fieldName].showError();
          setTimeout(() => {
            form.initFormFields(condition);
          }, 100);
          return false;
        }
        const params = {
          contacterId,
          fieldName,
          oldValue: oldvalue,
          newValue: value,
          fieldType: fit,
        };
        contacterEdit(params);
      }
    }
    onEditChange2 = (oldvalue = '', field, value) => {
      const { contacterId, contacterEdit, condition, form } = this.props.contacterViewStore;
      const fit = field.conditionType.toUpperCase();
      const fieldName = field.domkey[0];
      if (value !== oldvalue) {
        if (field.viewAttr == 3 && value == '') {
          this.refs[fieldName].showError();
          setTimeout(() => {
            form.initFormFields(condition);
          }, 100);
          return false;
        }
        const params = {
          contacterId,
          fieldName,
          oldValue: oldvalue,
          newValue: value,
          fieldType: fit,
        };
        contacterEdit(params);
      }
    }
}

export default WeaTools.tryCatch(React,
  props => <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@ejstl7`} msg={props.error ? props.error : getLabel(129417, '服务器运行出错，请联系系统管理员！')} />,
  { error: '' },
)(ContacterView);
